package reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reggie.common.CustomException;
import reggie.entity.Setmeal;
import reggie.entity.SetmealDish;
import reggie.entity.SetmealDto;
import reggie.mapper.SetmealMapper;
import reggie.service.SetmealDishService;
import reggie.service.SetmealService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: SetmealServiceImpl <br/>
 * Description: <br/>
 * date: 2022/12/1 22:06<br/>
 *
 * @author Xingyingsheng<br />
 * @since JDK 11
 */
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
   @Autowired
    private SetmealDishService setmealDishService;



    /**
     * 新增套餐，同时保存套餐和菜品的关联信息
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
            this.save(setmealDto);

        List<SetmealDish> list = setmealDto.getSetmealDishes();
        list.stream().map(item->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(list);
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
//        select count(*) from setmeal where id in (1,2,3) and status=1;
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.in(Setmeal::getId,ids).eq(Setmeal::getStatus,1);

        int count = this.count(lambdaQueryWrapper);

        if (count>0){
           throw new CustomException("套餐正在售卖，不能删除");
        }
        this.removeByIds(ids);
//      delete from setmeal dish where setmeal_id in (1,2,3)
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapper);

    }
}
